package com.wr.controller.article;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.wr.cmmon.UserContext;
import com.wr.config.Sender;
import com.wr.constant.GlobalConstant;
import com.wr.controller.user.UserHelper;
import com.wr.model.*;
import com.wr.service.MailServiceImpl;
import com.wr.service.article.ArticleService;
import com.wr.service.comment.CommentService;
import com.wr.service.plate.PlateService;
import com.wr.service.user.UserService;
import com.wr.utils.AccountValidatorUtil;
import com.wr.utils.CommonUtil;
import com.wr.utils.PageData;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author weirong
 * @Title:
 * @Description:
 * @date 2018/6/1118:17
 */

@Controller
@RequestMapping("blog")
public class ArticleController {

    Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private MailServiceImpl mailService;

    private String sessionCode = "user:register:code";

    private String sessionLoginCode = "user:login:code";
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ArticleService articleService;
    @Autowired
    private PlateService plateService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private Sender sender;

    @RequestMapping("toAdd")
    public String toAdd(Model model) {

        Plate plate = new Plate();
        plate.setId(1);
        List<Plate> plates = plateService.list(plate);
        model.addAttribute("plates", plates);
        return "blog/add_blog";
    }

    @RequestMapping("add")
    @ResponseBody
    public HashMap<String,Object> add(Article article) {
        HashMap<String,Object> msg = Maps.newHashMap();
        if(StringUtils.isBlank(article.getTitle())) {
            msg.put("code",1);
            msg.put("msg","博客标题不能为空!");
            return msg;
        }
        if(article.getTitle().length() > 50) {
            msg.put("code",1);
            msg.put("msg","博客标题不能大于50个字");
            return msg;
        }
        if(article.getPlateid() == null) {
            msg.put("code",1);
            msg.put("msg","板块不能为空!");
            return msg;
        }
        if(StringUtils.isBlank(article.getContent())) {
            msg.put("code",1);
            msg.put("msg","博客内容不能为空!");
            return msg;
        }
        if(article.getContent().length() > 4000000) {
            msg.put("code",1);
            msg.put("msg","博客内容不能大于4000000个字");
            return msg;
        }

        User user = UserContext.getUser();
        article.setUserid(user.getId());
        article.setUserName(user.getUsername());
        try {
            RestResponse<Article> rest = articleService.add(article);
            Article a = rest.getResult();
            msg.put("code",0);
            msg.put("msg","/blog/detail/"+a.getId());
            return msg;
        } catch (Exception e) {
            logger.error(e,e);
            msg.put("code",1);
            msg.put("msg","系统异常，联系客服");
            return msg;
        }

    }

    @RequestMapping("detail/{id}")
    public String detail(Model model,@PathVariable Integer id) {

        Article article = articleService.detail(id);
        model.addAttribute("article",article);
        try{
            JSONObject comments = commentService.listByArtId(article.getId(),1);
            long total = comments.getLong("total");
            JSONArray rows = comments.getJSONArray("rows");
            List<Comment> commentList = JSONArray.parseArray(JSON.toJSONString(rows),Comment.class);
            for(Comment c:commentList) {
                RestResponse<User> rest = userService.getUserById(c.getUserid());
                if(rest.getCode() == RestCode.OK.code) {
                    User user = rest.getResult();
                    if(user != null) {
                        c.setAvatar(user.getAvatar());
                    }
                }
            }
            model.addAttribute("comments",commentList);
            model.addAttribute("commentCount",total);
        } catch (Exception e) {

        }

        return "blog/detail_blog";
    }

    @PostMapping("upBlogViewCount")
    public void upBlogViewCount(Integer id) {
        sender.send(id);
    }

    @PostMapping("jsonList")
    @ResponseBody
    public List<Article> jsonList(String pageNo) {
        if(StringUtils.isBlank(pageNo)) {
            pageNo = "1";
        }
        List<Article> articles = articleService.mainList(Integer.parseInt(pageNo),5);

        return articles;
    }

    @PostMapping("rightList")
    @ResponseBody
    public List<Article>  rightList(Integer flag) {

        PageData pd = new PageData();
        String order = "viewCount";
        Integer limitNum = 5;
        if(flag == 1) {
            order = "createTime";
        }
        pd.put("order",order);
        pd.put("limitNum",limitNum);

        List<Article> articles = articleService.listPd(pd);

        return articles;
    }
}
